import React, { useEffect, useState } from 'react'
import { IAuthLoader } from '@/router/AuthLoader'
import { IMenuItem } from '@/types/menu'
import { Breadcrumb } from 'antd'
import type { BreadcrumbItemType } from 'antd/es/breadcrumb/Breadcrumb'
import { useLocation, useRouteLoaderData } from 'react-router-dom'

const BreadCrumb: React.FC = () => {
  const [breadList, setBreadList] = useState<BreadcrumbItemType[]>([])

  const getItem = (item: IMenuItem): BreadcrumbItemType => {
    return { title: item.menuName }
  }
  const { pathname } = useLocation()
  const { menuList } = useRouteLoaderData('root') as IAuthLoader

  /**
   * 递归查找
   * @param tree
   * @param pathname
   * @param paths
   * @returns
   */
  const findTreeNode = (tree: IMenuItem[], pathname: string, paths: IMenuItem[] = []): IMenuItem[] => {
    for (let i = 0; i < tree.length; i++) {
      const treeItem = tree[i]
      paths.push(treeItem)
      // 查找第一层
      if (treeItem.path === pathname) return paths
      // 递归查找第二层
      if (treeItem.children && treeItem.children.length) {
        const list = findTreeNode(treeItem.children, pathname, paths)
        if (list && list.length) {
          return list
        }
      }
      paths.pop()
    }
    return []
  }

  useEffect(() => {
    const list = findTreeNode(menuList, pathname, [])
    setBreadList(list.map(item => getItem(item)))
  }, [pathname])

  return <Breadcrumb items={breadList}></Breadcrumb>
}

export default BreadCrumb
